<template>
  <div>
    <h1> {{id? '编辑': '新建'}}广告</h1>
    <el-form label-width='100px' @submit.native.prevent='save'>
      <el-form-item label='分类名称'>
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label='广告'>
        <el-button type='primary' plain @click="model.items.push({})" size='small'><i class='el-icon-plus'>添加广告</i>
        </el-button>
        <el-row type='flex' style="flex-wrap:wrap">
          <el-col :md=12 v-for="(item, i) in model.items" :key='i'>
            <el-form-item label='URL'>
              <el-input v-model="item.url"></el-input>
            </el-form-item>
            <el-form-item label='Banner' style="marginTop:0.5rem">
              <el-upload class="avatar-uploader" :action="uploadUrl" :headers="getAuthorization()" :show-file-list="false"
                :on-success="res=>$set(item, 'image', res.url)">
                <img v-if="item.image" :src="item.image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type='danger' @click="model.items.splice(i, 1)" size='small'>删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <!-- native-type: 表示其原生类型是submit -->
        <el-button type='primary' native-type='submit'>保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  props: {
    id: {},
  },
  data() {
    return {
      model: {
        items: [],
      },
    };
  },
  methods: {
    async save() {
      let res;
      if (this.id) {
        // id存在则证明此时是编辑保存操作 => 更新数据
        res = await this.$http.put(`rest/ads/${this.id}`, this.model);
      } else {
        // 否则是新建保存操作 => 新增
        res = await this.$http.post("rest/ads", this.model);
      }
      if (res.data) {
        this.$message({
          type: "success",
          message: "保存成功",
        });
        this.$router.push("/ads/list");
      }
    },
    // 根据id查询分类信息
    async fetchById() {
      const res = await this.$http.get(`rest/ads/${this.id}`);
      this.model = res.data;
    },
  },
  created() {
    if (this.id) {
      this.fetchById();
    }
  },
};
</script>